<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/30
 * Time: 10:22
 */

namespace common\components\ActionsComponents;
use common\components\DataHelper;
use common\models\Merchant\Merchant;


/**
 * 添加独立操作
 * Class InsertAction
 * @package common\components\ActionsComponents
 */
class InsertAction extends CommonAction
{
    public $message = '添加成功!';

    public $return = [];

    public function run()
    {
        $model = new $this->model();
        $controller = $this->controller;
        $result = $model->addCommon($this->_request, $this->scenarios);

        if ( !empty($this->return) && $result ) {
            foreach ( $this->return as $value ) {
                if ( isset($model->$value) ) {
                    $this->data[$value] = $model->$value;
                }
            }
        }

        if ( $result ) {
            if ( $this->isPushLocal ) {
                DataHelper::local_pull_table(Merchant::getCurrentMerInfo('id'), $model::tableName(), $model[$model::primaryKey()[0]]);
            }
            //成功后回调处理
            if($this->callback instanceof \Closure){
                $fun = $this->callback;
                $fun($model[$model::primaryKey()[0]]);
            }
            return $controller->jsonResponse($controller::RESPONSE_SUCCESS, $this->message, $this->data);
        }

        return $controller->jsonResponse($controller::RESPONSE_FAILURE, $model->getFirstErrorToStr(), $model->getFirstErrors());
    }
}